import {
	defineStore
} from 'pinia'
import {
	getUserInfo,
	reqLogin
} from '@/service/modules/login.js'
import {
	rsaDecrypt
} from '@/utils/rsa'

export const useLoginStore = defineStore('login', {
	state: () => ({
		token: uni.getStorageSync('token') || {},
		userInfo: uni.getStorageSync('userInfo') || {},
	}),
	actions: {
		// 登录请求
		async loginAction(code) {
			const res = await reqLogin(code)
			const token = {
				name: res.data.tokenName,
				value: res.data.tokenValue
			}
			// 存储在仓库和本地
			this.token = token
			uni.setStorageSync('token', token)
			// 获取用户信息
			this.getUserInfoAction()
		},

		// 获取用户信息请求
		async getUserInfoAction() {
			const res = await getUserInfo()
			// 将信息解密
			const userInfo = rsaDecrypt(res.data)
			// 存储在本地和仓库
			uni.setStorageSync('userInfo', userInfo)
			this.userInfo = userInfo
		}
	}
})